package com.azzcs.spring.factory.config;

import com.azzcs.spring.bean.AnnotatedBeanDefinition;
import com.azzcs.spring.bean.BeanDefinition;
import com.azzcs.spring.factory.DefaultListableBeanFactory;

import java.util.Set;

import static com.azzcs.spring.utils.ClassUtil.getClasses;

/**
 * @Author: wzg
 * @Date: 2020/12/19 下午5:04
 */
public class ConfigurationClassPostProcessor implements BeanFactoryPostProcessor{

    private BeanDefinition beanDefinition;
    private DefaultListableBeanFactory beanFactory;

    public ConfigurationClassPostProcessor(BeanDefinition beanDefinition) {
        this.beanDefinition = beanDefinition;
    }

    @Override
    public void postProcessBeanFactory(DefaultListableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
        Set<String> basePackages = beanDefinition.getBasePackages();
        for (String basePackage : basePackages) {
            this.processConfigBeanDefinitions(basePackage);
        }
    }

    // 解析 基础包 加载 BeanDefinitions
    public void processConfigBeanDefinitions(String basePackage) {
        Set<Class<?>> classes = getClasses(basePackage);
        for (Class<?> clazz : classes) {
            BeanDefinition beanDefinition = new AnnotatedBeanDefinition(clazz);
            if (beanDefinition.isBean()) {
                beanFactory.doRegisterBean(beanDefinition);
            }
        }
    }


}
